/*!
shared handle for multi-thread
- 维护配置文件和行情数据
- 使用std::sync::Rwlock, 而没有使用tokio::sync::RwLock, 因为虽然前者会导致阻塞，但是因为egui是同步的，所以更方便调用。对于程序应用场景而言，阻塞没有影响。

*/

use crate::*;
use chrono::Local;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use anyhow::bail;
use sqlx::sqlite::SqlitePool;
use tokio::sync::{ mpsc::{Receiver, Sender},  Mutex};
/**
多线程共享数据句柄
 */
pub struct Shared {
    pub startup : String,
    pub cfg_file: String,
    pub cfg: Config,    
    pub dataset : std::sync::RwLock< Vec<Task> >,
    pub dbpool: SqlitePool,   
    /// 任务发送接收器
    pub tx: Sender<WorkTask>,
    pub rx: Mutex<Receiver<WorkTask>>,    
}

impl Shared {
    pub fn new(cfg_file: &str, dbpool: SqlitePool ) -> Self {

        let cfg_file = cfg_file.to_string();    
        let src = String::from_utf8(std::fs::read(&cfg_file).unwrap()).unwrap();
        let cfg: Config = serde_json::from_str(src.as_str()).unwrap();       
        //let server_uri = server_uri.to_string();
        //let site_root = site_root.to_string();        
        let startup = Local::now().format("%Y%m%d %H:%M:%S").to_string();

        let (tx, rx) = tokio::sync::mpsc::channel(16);

        Self {           
            startup,
            cfg_file,
            cfg,
            dataset: std::sync::RwLock::new(vec![]),            
            dbpool,
            rx: Mutex::new(rx),
            tx,
        }
    }
}

#[derive(Debug, Clone)]
pub enum WorkTask {
    SendMessage(String),
    Unknown(),
}
